package com.ruoyi.web.controller.pack;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.pack.domain.PackLocationLog;
import com.ruoyi.pack.domain.dto.CityTransitAnalysisDto;
import com.ruoyi.pack.service.IPackLocationLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 定位日志Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Api(tags = "定位日志管理")
@RestController
@RequestMapping("/pack/locationLog")
public class PackLocationLogController extends BaseController
{
    @Autowired
    private IPackLocationLogService packLocationLogService;

    /**
     * 查询定位日志列表
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:list')")
    @GetMapping("/list")
    @ApiOperation("查询定位日志列表")
    public TableDataInfo list(PackLocationLog packLocationLog)
    {
        startPage();
        List<PackLocationLog> list = packLocationLogService.selectPackLocationLogListWithTransportPlan(packLocationLog);
        return getDataTable(list);
    }

    /**
     * 导出定位日志列表
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:export')")
    @Log(title = "定位日志", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出定位日志列表")
    public void export(HttpServletResponse response, PackLocationLog packLocationLog)
    {
        List<PackLocationLog> list = packLocationLogService.selectPackLocationLogList(packLocationLog);
        ExcelUtil<PackLocationLog> util = new ExcelUtil<PackLocationLog>(PackLocationLog.class);
        util.exportExcel(response, list, "定位日志数据");
    }

    /**
     * 获取定位日志详细信息
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:query')")
    @GetMapping(value = "/{logId}")
    @ApiOperation("获取定位日志详细信息")
    public AjaxResult getInfo(@PathVariable("logId") Long logId)
    {
        return success(packLocationLogService.selectPackLocationLogByLogId(logId));
    }

    /**
     * 新增定位日志
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:add')")
    @Log(title = "定位日志", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增定位日志")
    public AjaxResult add(@RequestBody PackLocationLog packLocationLog)
    {
        return toAjax(packLocationLogService.insertPackLocationLog(packLocationLog));
    }

    /**
     * 修改定位日志
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:edit')")
    @Log(title = "定位日志", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改定位日志")
    public AjaxResult edit(@RequestBody PackLocationLog packLocationLog)
    {
        return toAjax(packLocationLogService.updatePackLocationLog(packLocationLog));
    }

    /**
     * 删除定位日志
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:remove')")
    @Log(title = "定位日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{logIds}")
    @ApiOperation("删除定位日志")
    public AjaxResult remove(@PathVariable Long[] logIds)
    {
        return toAjax(packLocationLogService.deletePackLocationLogByLogIds(logIds));
    }

    /**
     * 分析城市运输情况
     * 
     * @param departureCity 出发地城市名
     * @param destinationCity 目的地城市名
     * @return 城市运输分析结果
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:analysis')")
    @GetMapping("/analysis/cityTransit")
    @ApiOperation("分析从出发地到目的地的城市运输情况")
    public AjaxResult analyzeCityTransit(
            @ApiParam(value = "出发地城市名", required = true, example = "北京")
            @RequestParam("departureCity") String departureCity,
            @ApiParam(value = "目的地城市名", required = true, example = "上海") 
            @RequestParam("destinationCity") String destinationCity)
    {
        try {
            // 参数校验
            if (departureCity == null || departureCity.trim().isEmpty()) {
                return error("出发地城市名不能为空");
            }
            if (destinationCity == null || destinationCity.trim().isEmpty()) {
                return error("目的地城市名不能为空");
            }
            if (departureCity.equals(destinationCity)) {
                return error("出发地和目的地不能相同");
            }

            // 调用分析服务
            CityTransitAnalysisDto result = packLocationLogService.analyzeCityTransit(
                departureCity.trim(), destinationCity.trim());
            
            if (result.getWayBillCount() == 0) {
                return warn("未找到从 " + departureCity + " 到 " + destinationCity + " 的运输记录");
            }
            
            return success(result);
            
        } catch (Exception e) {
            logger.error("城市运输分析失败: {} -> {}", departureCity, destinationCity, e);
            return error("分析失败: " + e.getMessage());
        }
    }

    /**
     * 获取可用城市列表（用于测试界面的下拉选择）
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:query')")
    @GetMapping("/analysis/cities")
    @ApiOperation("获取可用城市列表")
    public AjaxResult getAvailableCities()
    {
        try {
            // 查询数据库中所有的城市名称（去重）
            PackLocationLog queryParam = new PackLocationLog();
            List<PackLocationLog> logs = packLocationLogService.selectPackLocationLogList(queryParam);
            
            List<String> cities = logs.stream()
                .filter(log -> log.getCity() != null && !log.getCity().trim().isEmpty())
                .map(log -> log.getCity().trim())
                .distinct()
                .sorted()
                .collect(java.util.stream.Collectors.toList());
            
            return success(cities);
            
        } catch (Exception e) {
            logger.error("获取城市列表失败", e);
            return error("获取城市列表失败: " + e.getMessage());
        }
    }

    /**
     * 测试接口 - 用于验证城市运输分析功能
     */
    @PreAuthorize("@ss.hasPermi('pack:locationLog:test')")
    @GetMapping("/test/cityTransit")
    @ApiOperation("测试城市运输分析功能")
    public AjaxResult testCityTransit()
    {
        try {
            // 预设一些测试用例
            String[][] testCases = {
                {"北京", "上海"},
                {"上海", "广州"},
                {"深圳", "北京"},
                {"杭州", "成都"}
            };
            
            List<Object> testResults = new java.util.ArrayList<>();
            
            for (String[] testCase : testCases) {
                String departure = testCase[0];
                String destination = testCase[1];
                
                try {
                    CityTransitAnalysisDto result = packLocationLogService.analyzeCityTransit(departure, destination);
                    
                    java.util.Map<String, Object> testResult = new java.util.HashMap<>();
                    testResult.put("departure", departure);
                    testResult.put("destination", destination);
                    testResult.put("success", true);
                    testResult.put("wayBillCount", result.getWayBillCount());
                    testResult.put("totalTransitTime", result.getTotalTransitTime());
                    testResult.put("passedCitiesCount", result.getPassedCities().size());
                    
                    testResults.add(testResult);
                    
                } catch (Exception e) {
                    java.util.Map<String, Object> testResult = new java.util.HashMap<>();
                    testResult.put("departure", departure);
                    testResult.put("destination", destination);
                    testResult.put("success", false);
                    testResult.put("error", e.getMessage());
                    
                    testResults.add(testResult);
                }
            }
            
            java.util.Map<String, Object> response = new java.util.HashMap<>();
            response.put("testCases", testResults.size());
            response.put("results", testResults);
            
            return success(response);
            
        } catch (Exception e) {
            logger.error("测试城市运输分析功能失败", e);
            return error("测试失败: " + e.getMessage());
        }
    }
}